// rescue.ts - 救援状态跟踪页面
Page({
  data: {
    requestId: '',
    currentStep: 2, // 当前进度步骤
    rescueStatus: null as any,
    rescueRequest: null as any,
    rescuerInfo: null as any,
    rescuerLocation: null as any,
    statusText: '正在匹配救援资源',
    statusDescription: '我们正在为您匹配最合适的救援方案，请稍候...',
    rescueTypeText: '',
    urgencyText: '',
    eta: 15,
    refreshing: false,
    
    // 地图相关
    mapMarkers: [] as any[],
    polyline: [] as any[],
  },

  /**
   * 页面加载
   */
  onLoad(options: any) {
    const requestId = options.requestId
    if (requestId) {
      this.setData({
        requestId: requestId
      })
      this.loadRescueStatus()
    }
  },

  /**
   * 加载救援状态
   */
  loadRescueStatus() {
    wx.showLoading({
      title: '加载中...'
    })

    // 模拟从API获取救援状态
    setTimeout(() => {
      const mockRescueData = this.generateMockRescueData()
      this.setData({
        rescueStatus: mockRescueData.status,
        rescueRequest: mockRescueData.request,
        rescuerInfo: mockRescueData.rescuer,
        rescuerLocation: mockRescueData.location
      })
      
      this.updateStatusText()
      this.updateMapMarkers()
      
      wx.hideLoading()
    }, 1000)
  },

  /**
   * 生成模拟救援数据
   */
  generateMockRescueData() {
    const now = new Date()
    const submitTime = new Date(now.getTime() - 10 * 60 * 1000) // 10分钟前提交
    const matchTime = new Date(now.getTime() - 8 * 60 * 1000)   // 8分钟前匹配
    
    return {
      status: {
        submitTime: this.formatTime(submitTime),
        matchTime: this.formatTime(matchTime),
        confirmTime: '',
        departTime: '',
        arriveTime: '',
        completeTime: ''
      },
      request: {
        type: 'ambulance',
        startLocation: '北京市朝阳区国贸CBD',
        endLocation: '北京协和医院',
        selectedTime: '立即用车',
        urgencyLevel: 'high',
        passengerCount: 2,
        phoneNumber: '138****8000'
      },
      rescuer: {
        name: '张医生',
        title: '主治医师',
        workId: 'BJ001',
        avatar: '../../images/doctor-avatar.jpg',
        phone: '400-123-4567'
      },
      location: {
        latitude: 39.908823,
        longitude: 116.397470
      }
    }
  },

  /**
   * 更新状态文本
   */
  updateStatusText() {
    const step = this.data.currentStep
    const request = this.data.rescueRequest
    
    let statusText = ''
    let statusDescription = ''
    let rescueTypeText = ''
    let urgencyText = ''
    
    // 救援类型文本
    const typeMap: Record<string, string> = {
      'ambulance': '🚑 救护车',
      'train': '🚄 高铁转运',
      'plane': '✈️ 民用航班',
      'medical_plane': '🏥 医疗飞机',
      'helicopter': '🚁 直升机'
    }
    rescueTypeText = request && request.type ? (typeMap[request.type] || '救援服务') : '救援服务'
    
    // 紧急程度文本
    const urgencyMap: Record<string, string> = {
      'low': '低 (两天内)',
      'medium': '中 (一天内)',
      'high': '高 (三小时内)'
    }
    urgencyText = request && request.urgencyLevel ? (urgencyMap[request.urgencyLevel] || '标准') : '标准'
    
    // 状态文本
    switch(step) {
      case 1:
        statusText = '申请已提交'
        statusDescription = '您的救援申请已成功提交，系统正在处理中...'
        break
      case 2:
        statusText = '正在匹配资源'
        statusDescription = '我们正在为您匹配最合适的救援方案，预计2-5分钟完成匹配...'
        break
      case 3:
        statusText = '等待确认'
        statusDescription = '已为您匹配到救援资源，救援人员正在确认接单...'
        break
      case 4:
        statusText = '救援人员出发'
        statusDescription = '救援人员已确认并出发，预计15分钟后到达现场...'
        break
      case 5:
        statusText = '即将到达'
        statusDescription = '救援人员即将到达现场，请准备好相关物品...'
        break
      case 6:
        statusText = '救援完成'
        statusDescription = '救援任务已圆满完成，感谢您的信任！'
        break
    }
    
    this.setData({
      statusText,
      statusDescription,
      rescueTypeText,
      urgencyText
    })
  },

  /**
   * 更新地图标记
   */
  updateMapMarkers() {
    const rescuerLocation = this.data.rescuerLocation
    if (!rescuerLocation) return
    
    const markers = [
      {
        id: 1,
        latitude: rescuerLocation.latitude,
        longitude: rescuerLocation.longitude,
        iconPath: '../../images/ambulance-marker.png',
        width: 40,
        height: 40,
        title: '救援车辆'
      }
    ]
    
    this.setData({
      mapMarkers: markers
    })
  },

  /**
   * 联系救援人员
   */
  callRescuer() {
    const rescuer = this.data.rescuerInfo
    if (!rescuer) return
    
    wx.showModal({
      title: '联系救援人员',
      content: `是否拨打 ${rescuer.name} 的电话？`,
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: rescuer.phone,
            fail: () => {
              wx.showToast({
                title: '拨号失败',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },

  /**
   * 刷新状态
   */
  refreshStatus() {
    this.setData({
      refreshing: true
    })
    
    setTimeout(() => {
      // 模拟状态更新
      let newStep = this.data.currentStep
      if (newStep < 6) {
        newStep += Math.random() > 0.5 ? 1 : 0
      }
      
      this.setData({
        currentStep: newStep,
        refreshing: false
      })
      
      this.updateStatusText()
      
      wx.showToast({
        title: '状态已更新',
        icon: 'success'
      })
    }, 1500)
  },

  /**
   * 联系客服
   */
  contactSupport() {
    wx.showModal({
      title: '客服电话',
      content: '如需帮助，请拨打24小时客服热线：400-123-4567',
      confirmText: '拨打',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '400-123-4567',
            fail: () => {
              wx.showToast({
                title: '拨号失败',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },

  /**
   * 格式化时间
   */
  formatTime(date: Date): string {
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `${hours}:${minutes}`
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadRescueStatus()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 2000)
  },

  /**
   * 页面分享
   */
  onShareAppMessage() {
    return {
      title: '立体救援 - 我正在使用救援服务',
      path: '/pages/index/index'
    }
  }
})
